package com.kun.kunkunmall.ware.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kun.common.exception.NoStockException;
import com.kun.common.to.OrderTo;
import com.kun.common.to.StockDetailTo;
import com.kun.common.to.StockLockedTo;
import com.kun.common.utils.R;
import com.kun.kunkunmall.ware.entity.WareOrderTaskDetailEntity;
import com.kun.kunkunmall.ware.entity.WareOrderTaskEntity;
import com.kun.kunkunmall.ware.feign.OrderFeignService;
import com.kun.kunkunmall.ware.feign.ProductFeignService;
import com.kun.common.to.SkuHasStockVo;
import com.kun.kunkunmall.ware.service.WareOrderTaskDetailService;
import com.kun.kunkunmall.ware.service.WareOrderTaskService;
import com.kun.kunkunmall.ware.vo.OrderItemVo;
import com.kun.kunkunmall.ware.vo.OrderVo;
import com.kun.kunkunmall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.utils.PageUtils;
import com.kun.common.utils.Query;

import com.kun.kunkunmall.ware.dao.WareSkuDao;
import com.kun.kunkunmall.ware.entity.WareSkuEntity;
import com.kun.kunkunmall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
@RabbitListener(queues = "stock.release.stock.queue")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private OrderFeignService orderFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isBlank(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isBlank(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 判断如果还没有库存记录，就是新增操作
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("sku_id", skuId).eq("ware_id", wareId);
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(wrapper);
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // 远程查询sku的名字，如果失败整个事务无需回滚
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> map = (Map<String, Object>) info.get("data");
                if (info.getCode() == 0) {

                    wareSkuEntity.setSkuName((String) map.get("skuName"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            this.baseMapper.insert(wareSkuEntity);
        } else {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(skuId);
            skuHasStockVo.setHasStock(count != null && count > 0);
            skuHasStockVo.setSkuId(skuId);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }


    /**
     * 库存解锁场景
     * 下订单成功，订单过期没有支付被系统取消或者被用户手动取消
     * 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前锁定的库存就要解锁
     * 这里不使用seata的分布式事务，在高并发场景下，我们只需要达到最终一致性就可以了。
     *
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class) // 默认只要是运行时异常都会回滚
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单详情，为了方便追溯
         */
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        orderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(orderTaskEntity);


        // TODO 进阶版：按照下单的收货地址，找到一个就近仓库，锁定库存
        // 1. 找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            // 查询商品在哪个仓库里面又库存
            List<Long> wareIds = this.baseMapper.listWareHasStockIds(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());

        // 2. 锁定库存
        for (SkuWareHasStock stock : collect) {
            boolean skuStocked = false; // 用来判断锁定库存是否成功
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            // 先判断仓库是否有改商品
            if (wareIds == null || wareIds.size() == 0) {
                // 没有任何仓库有改商品
                throw new NoStockException(skuId);
            }
            // 开始锁定库存
            for (Long wareId : wareIds) {
                Long count = this.baseMapper.lockSkuStock(skuId, wareId, stock.getNum()); // 成功就返回1，否则就返回0
                if (count == 1) {
                    skuStocked = true;
                    //告诉MQ锁定成功
                    WareOrderTaskDetailEntity orderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", stock.getNum(), orderTaskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(orderTaskDetailEntity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(orderTaskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    // 只记录工作单id是不行的，前面一旦发生回滚，就无法查到对应的工作单数据
                    BeanUtil.copyProperties(orderTaskDetailEntity, stockDetailTo);
                    lockedTo.setDetailTo(stockDetailTo);
                    // 如果每一个商品锁定成功，就将当前商品锁了几件的工作单详情发送给MQ
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                    break;
                }
                // 当前仓库锁定失败，重试下一个仓库
            }
            // 判断库存锁定是否成功
            if (!skuStocked) {
                // 当前商品所有仓库都没有锁住库存，前面保存的工作单的信息就回滚了
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockWareStock(StockLockedTo stockLockedTo, Message message, Channel channel) {
        System.out.println("收到解锁库存的消息");
        Long id = stockLockedTo.getId(); // 库存工作单的id
        StockDetailTo detailTo = stockLockedTo.getDetailTo(); // 库存工作单的详细信息

        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailTo.getId());
        if (byId != null) {
            // 只表明库存锁定成功了，要不要解锁还需要另行判断
            // 1.没有该订单，说明没有此订单，必须解锁
            // 2.有这个订单，要看订单状态（已取消：需要解锁库存，没取消，不能解锁库存）
            Long lockedToId = stockLockedTo.getId();
            WareOrderTaskEntity orderTask = wareOrderTaskService.getById(lockedToId);
            String orderSn = orderTask.getOrderSn(); // 拿到订单号
            // 查询订单的状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                // 订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus() == 6) {
                    // 订单已经被取消了，需要解锁库存
                    if (byId.getLockStatus() == 1) {
                        unlockStock(detailTo.getSkuId(), detailTo.getSkuNum(), detailTo.getWareId(), detailTo.getId());
                    }

                }
            } else {
                // 消息拒绝重新放入到队列里面
                throw new RuntimeException("远程服务失败");
            }
        } else {
            // 无需解锁

        }
    }


    /**
     * 防止订单服务卡顿，导致订单状态一直修改不了，导致无法解锁库存
     * @param to
     */
    @Override
    public void unlockWareStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        // 订单解锁了，才会来到这里。
        // 查询库存的状态，防止重复解锁库存
       WareOrderTaskEntity taskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);

        Long taskEntityId = taskEntity.getId();
        // 按照库存工作单，找到所以头没有解锁库存
        List<WareOrderTaskDetailEntity> entityList = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskEntityId).eq("lock_status", 1));

        // 解锁库存
        for (WareOrderTaskDetailEntity entity : entityList) {
            unlockStock(entity.getSkuId(),entity.getSkuNum(),entity.getWareId(),entity.getTaskId());
        }

    }


    /**
     * 真正解锁库存的方法
     *
     * @param skuId
     * @param num
     * @param wareId
     * @param taskId
     */
    private void unlockStock(Long skuId, Integer num, Long wareId, Long taskId) {
        this.baseMapper.unlockStock(skuId, num, wareId);
        // 更新库存工作单的状态
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskId);
        wareOrderTaskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }


    @Data
    static class SkuWareHasStock {
        private Long skuId; // 商品id
        private List<Long> wareId; // 哪些仓库包含此商品
        private Integer num; // 需要锁定的库存数量
    }

}